const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    time: 15,
    jp: "",
    imgList: [],
    images: [],
    name: false,
    KJRS: false,
    ZJRS: false,
    weixin: false,
    JESHOU: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  //奖品名称
  JPNAME: function (e) {
    this.setData({
      name: e.detail.value
    })
  },
    //开奖人数
  KJRS: function (e) {
    this.setData({
      KJRS: e.detail.value
    })
  },
    //中奖人数
  ZJRS: function (e) {
    this.setData({
      ZJRS: e.detail.value
    })
  },
    //中奖用户联系领奖微信号
  weixin: function (e) {
    this.setData({
      weixin: e.detail.value
    })
  },
  //填写介绍内容
  JESHOU: function (e) {
    this.setData({
      JESHOU: e.detail.value
    })
  },
  //选择图片
  ChooseImage() {
    wx.chooseImage({
      count: 5 - this.data.imgList.length,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        
        if (this.data.imgList.length != 0) {
          this.setData({
            imgList: this.data.imgList.concat(res.tempFilePaths)
          })
        } else {
          this.setData({
            imgList: res.tempFilePaths
          })
        }
     
      }
    });
  },
  //删除图片
  DeleteImg(e) {
    wx.showModal({
      title: '要删除这张照片吗？',
      content: '',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList: this.data.imgList
          })
        }
      }
    })
  },
  //判断是否填写
  bcXY(e) {
    let that = this
    let name = that.data.name
    let KJRS = that.data.KJRS
    let ZJRS = that.data.ZJRS
    let weixin = that.data.weixin
    let JESHOU = that.data.JESHOU
    if (name == false) {
      wx.showToast({
        title: '标题未填',
        icon: 'none',
        duration: 2000
      })
      return
    }
    if (weixin == false) {
      wx.showToast({
        title: '联系微信号未填',
        icon: 'none',
        duration: 2000
      })
      return
    }
    if (KJRS == false) {
      wx.showToast({
        title: '满多少人数开奖未填',
        icon: 'none',
        duration: 2000
      })
      return
    }
    if (ZJRS == false) {
      wx.showToast({
        title: '中奖人数未填',
        icon: 'none',
        duration: 2000
      })
      return
    }
    console.log(KJRS, ZJRS)
    if (KJRS < ZJRS) {
      wx.showToast({
        title: '开奖人数小于中奖人数',
        icon: 'none',
        duration: 2000
      })
      return
    }
    if (JESHOU == false) {
      wx.showToast({
        title: '介绍内容未填',
        icon: 'none',
        duration: 2000
      })
      return
    }
    wx.getUserProfile({
      desc: '用于完善会员资料',
      success: (res) => {
        console.log(res)
        let list = {
          name: name,
          KJRS: KJRS,
          ZJRS: ZJRS,
          weixin: weixin,
          JESHOU: JESHOU,
          nickName: res.userInfo.nickName,
          avatarUrl: res.userInfo.avatarUrl
        }
        if (that.data.imgList.length > 0) {
       
          that.adda(list)
        } else {
         
          that.addb(list)
        }
      }
    })

  },
//上传数据到数据库
  adda(list) {
    wx.showLoading({
      title: '发布中',
    })
    const promiseArr = []
    //只能一张张上传 遍历临时的图片数组
    for (let i = 0; i < this.data.imgList.length; i++) {
      let filePath = this.data.imgList[i]
      let suffix = /\.[^\.]+$/.exec(filePath)[0]; // 正则表达式，获取文件扩展名
      //在每次上传的时候，就往promiseArr里存一个promise，只有当所有的都返回结果时，才可以继续往下执行
      promiseArr.push(new Promise((reslove, reject) => {
        var that = this
        wx.cloud.uploadFile({
          cloudPath: new Date().getTime() + suffix,
          filePath: filePath, // 文件路径
          success: res => {
            console.log(res)
            //获取图片的http路径
            wx.cloud.getTempFileURL({
              fileList: [res.fileID],
              success: res => {
                console.log(res.fileList[0].tempFileURL)
                that.setData({
                  images: this.data.images.concat(res.fileList[0].tempFileURL)
                })
                reslove()
              },
              fail: console.error
            })

          },
          fail: console.error
        })
      }))
    }
    //保证所有图片都上传成功
    Promise.all(promiseArr).then(res => {
      wx.cloud.database().collection('active_list').add({
        data: {
          items: [
            {
              image: this.data.images[0],
              name: list.name,
              count: list.ZJRS
            }
          ],
          name: list.name,
          creater_info: {
            nickName: '小程序官方',
            avatarUrl: 'cloud://sc-2gygagf77e71a124.7363-sc-2gygagf77e71a124-1304542037/choujiang/礼物.png',
            weixin: list.weixin
          },
          rich_info: {
            content: list.JESHOU,
            images: this.data.images
          },
          draw_count: list.KJRS,
          total_count: 0,
          HJXY: false,
          SH: true,
          time_order: new Date().getTime(),
          control:'是'
        },
        success(res) {
          wx.showToast({
            title: '发布成功',
            icon: 'success',
            duration: 2000
          })
          setTimeout(function () {
            wx.hideLoading()
          }, 2000)
          console.log('新增hf', res)

        },
        fail(res) {
          console.log('新增hf', res)
        }

      })
    })
  },
  addb(list) {
    wx.showLoading({
      title: '发布中',
    })
    wx.cloud.database().collection('active_list').add({
      data: {
        items: [
          {
            image: this.data.jp,
            name: list.name,
            count: list.ZJRS
          }
        ],
        name: list.name,
        creater_info: {
          nickName: '小程序官方',
          avatarUrl: 'cloud://sc-2gygagf77e71a124.7363-sc-2gygagf77e71a124-1304542037/choujiang/礼物.png',
          weixin: list.weixin
        },
        rich_info: {
          content: list.JESHOU
        },
        draw_count: list.KJRS,
        total_count: 0,
        HJXY: false,
        SH: true,
        time_order: new Date().getTime(),
        control:'是'
      },
      success(res) {
        wx.showToast({
          title: '发布成功',
          icon: 'success',
          duration: 2000
        })
        setTimeout(function () {
          wx.hideLoading()
        }, 2000)
        console.log('新增hf', res)
        wx.switchTab({
          url: '/pages/index/index',
        })
      },
      fail(res) {
        console.log('新增hf', res)
      }

    })

  },
  CPDJ() {
    this.data.Time = setInterval(() => {
      this.setData({
        time: --this.data.time
      })
      if (this.data.time <= 0) {
        clearInterval(this.data.Time)
        this.setData({
          time: 15
        })
        this.CP()
        this.CPDJ()
      }
    }, 800)
  },
  CP() {
    // 在页面中定义插屏广告
    let interstitialAd = null

    // 在页面onLoad回调事件中创建插屏广告实例
    if (wx.createInterstitialAd) {
      interstitialAd = wx.createInterstitialAd({
        adUnitId: app.data.adcp
      })
      interstitialAd.onLoad(() => { })
      interstitialAd.onError((err) => { })
      interstitialAd.onClose(() => { })
    }
    // 在适合的场景显示插屏广告
    if (interstitialAd) {
      interstitialAd.show().catch((err) => {
        console.error(err)
      })
    }
  },
  onShow(){

  }
})